package org.windey.applet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class WindeyServerConnection
{
	private Socket connectSocket ;
	private boolean connected;
	private BufferedReader in;
	private PrintWriter out;
	private String hostname ;
	private int port ;
	
	public WindeyServerConnection(String hostname, int port)
	{
		this.hostname = hostname ;
		this.port = port ;
		this.connected = false;
	}
	
	public void connect() throws WindeyServerConnectionException
	{
		try
		{
			connectSocket = new Socket(hostname, port);
			in = new BufferedReader(new InputStreamReader(connectSocket.getInputStream()));
			out = new PrintWriter(connectSocket.getOutputStream(), true);
			connected = true;
		}
		catch (NumberFormatException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
	}

	public void disconnect() throws WindeyServerConnectionException
	{
		try
		{
			if (connectSocket != null)
			{
				send("EOC");
				connectSocket.close();
				connected = false;
			}
		} 
		catch (IOException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}	
	}
	
	public boolean isConnected()
	{
		return this.connected;
	}
	
	public void send(String data)
	{
		out.println(data);
	}
	
	public String receive()
	{
		String result;
		try
		{
			result = in.readLine();
		}
		catch (SocketException e)
		{
			result = "EOC";
		}
		catch (IOException e)
		{
			result = "";
			e.printStackTrace();
		}
		return result;
	}
}
